'use client'

import { useState, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { MenuService, MenuItem, RolePermission } from '@/services/menuService'
import { 
  BookOpen, 
  Users, 
  FolderOpen, 
  Tags, 
  FileText, 
  BarChart3, 
  Settings,
  LayoutDashboard,
  Eye,
  Edit,
  Trash2,
  Plus,
  Save
} from 'lucide-react'

export default function MenuManagementPage() {
  const [allMenus, setAllMenus] = useState<MenuItem[]>([])
  const [rolePermissions, setRolePermissions] = useState<Record<string, RolePermission[]>>({})
  const [loading, setLoading] = useState(true)
  const [activeTab, setActiveTab] = useState('menus')

  useEffect(() => {
    fetchData()
  }, [])

  const fetchData = async () => {
    try {
      setLoading(true)
      const [menusResponse, permissionsResponse] = await Promise.all([
        MenuService.getAllMenus(),
        MenuService.getRolePermissions()
      ])

      if (menusResponse.code === 200) {
        setAllMenus(menusResponse.data)
      }

      if (permissionsResponse.code === 200) {
        setRolePermissions(permissionsResponse.data)
      }
    } catch (error) {
      console.error('获取数据失败:', error)
    } finally {
      setLoading(false)
    }
  }

  const getIconComponent = (iconName: string) => {
    const iconMap: Record<string, any> = {
      'DashboardOutlined': LayoutDashboard,
      'BookOutlined': BookOpen,
      'UserOutlined': Users,
      'FolderOutlined': FolderOpen,
      'TagsOutlined': Tags,
      'FileOutlined': FileText,
      'BarChartOutlined': BarChart3,
      'SettingOutlined': Settings,
    }
    return iconMap[iconName] || LayoutDashboard
  }

  const getPermissionBadge = (permission: RolePermission) => {
    return (
      <div className="flex items-center space-x-2">
        <Badge variant={permission.canView ? "default" : "secondary"}>
          <Eye className="h-3 w-3 mr-1" />
          查看
        </Badge>
        <Badge variant={permission.canEdit ? "default" : "secondary"}>
          <Edit className="h-3 w-3 mr-1" />
          编辑
        </Badge>
        <Badge variant={permission.canDelete ? "default" : "secondary"}>
          <Trash2 className="h-3 w-3 mr-1" />
          删除
        </Badge>
      </div>
    )
  }

  if (loading) {
    return (
      <div className="container mx-auto p-6 space-y-6">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold">菜单管理</h1>
            <p className="text-muted-foreground">管理系统导航菜单和角色权限</p>
          </div>
        </div>
        
        <div className="grid gap-6">
          {[...Array(3)].map((_, i) => (
            <Card key={i}>
              <CardHeader>
                <div className="h-6 bg-muted rounded animate-pulse w-1/3" />
                <div className="h-4 bg-muted rounded animate-pulse w-1/2" />
              </CardHeader>
              <CardContent>
                <div className="space-y-2">
                  {[...Array(4)].map((_, j) => (
                    <div key={j} className="h-4 bg-muted rounded animate-pulse" />
                  ))}
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      </div>
    )
  }

  return (
    <div className="container mx-auto p-6 space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">菜单管理</h1>
          <p className="text-muted-foreground">管理系统导航菜单和角色权限</p>
        </div>
        <Button>
          <Plus className="h-4 w-4 mr-2" />
          添加菜单
        </Button>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-2">
          <TabsTrigger value="menus">菜单配置</TabsTrigger>
          <TabsTrigger value="permissions">角色权限</TabsTrigger>
        </TabsList>

        <TabsContent value="menus" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>菜单列表</CardTitle>
              <CardDescription>当前系统中配置的所有菜单项</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {allMenus.map((menu) => {
                  const IconComponent = getIconComponent(menu.icon || '')
                  return (
                    <div key={menu.key} className="flex items-center justify-between p-4 border rounded-lg">
                      <div className="flex items-center space-x-3">
                        <IconComponent className="h-5 w-5 text-muted-foreground" />
                        <div>
                          <div className="font-medium">{menu.label}</div>
                          <div className="text-sm text-muted-foreground">
                            {menu.path} • {menu.key}
                          </div>
                        </div>
                      </div>
                      <div className="flex items-center space-x-2">
                        <Button variant="outline" size="sm">
                          <Edit className="h-4 w-4 mr-2" />
                          编辑
                        </Button>
                        <Button variant="outline" size="sm">
                          <Trash2 className="h-4 w-4 mr-2" />
                          删除
                        </Button>
                      </div>
                    </div>
                  )
                })}
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="permissions" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>角色权限配置</CardTitle>
              <CardDescription>配置不同角色对各个菜单的访问权限</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-6">
                {Object.entries(rolePermissions).map(([role, permissions]) => (
                  <div key={role} className="space-y-3">
                    <div className="flex items-center justify-between">
                      <h3 className="text-lg font-semibold capitalize">{role} 角色</h3>
                      <Button variant="outline" size="sm">
                        <Save className="h-4 w-4 mr-2" />
                        保存配置
                      </Button>
                    </div>
                    <div className="grid gap-3">
                      {permissions.map((permission) => (
                        <div key={permission.menuKey} className="flex items-center justify-between p-3 border rounded-lg">
                          <div className="flex items-center space-x-3">
                            <span className="font-medium">{permission.menuLabel}</span>
                            <span className="text-sm text-muted-foreground">({permission.menuKey})</span>
                          </div>
                          {getPermissionBadge(permission)}
                        </div>
                      ))}
                    </div>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  )
}
